﻿using System;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Ipmce.RemoteVoting.Common.Entities;

namespace Ipmce.RemoteVoting.Common.Tools
{
	public class VoteEncryptor : IVoteEncryptor
	{
		private readonly X509Certificate2 _certificate;

		public VoteEncryptor(X509Certificate2 certificate)
		{
			_certificate = certificate;
		}

		public byte[] Encrypt(Candidate candidate)
		{
			var data = PrepareData(candidate);
			var rsa = _certificate.PublicKey.Key as RSACryptoServiceProvider;
			return rsa.Encrypt(data, true);
		}

		public Candidate Decrypt(byte[] data)
		{
			var rsa = _certificate.PrivateKey as RSACryptoServiceProvider;
			var result = rsa.Decrypt(data, true);
			return new Candidate
			       	{
						Id = BitConverter.ToInt64(result, sizeof(int))
			       	};
		}

		private static byte[] PrepareData(Candidate candidate)
		{
			var randomizer = new Random(DateTime.Now.Millisecond);
			var random = new byte[2 * sizeof(int)];
			randomizer.NextBytes(random);
			return random.Take(sizeof (int)).Concat(BitConverter.GetBytes(candidate.Id)).Concat(random.Skip(sizeof (int))).ToArray();
		}
	}
}